package categorybrands

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"web/goods/api"
	"web/goods/forms"
	"web/goods/global"
	"web/goods/proto"
)

// 获取商品分类对应的全部品牌
func GetCategoryBrands(ctx *gin.Context) {
	idStr := ctx.Param("id")
	idInt, err := strconv.Atoi(idStr)
	if err != nil {
		zap.S().Error("strconv.Atoi：string转int类型发生错误")
		ctx.JSON(http.StatusNotFound, gin.H{
			"msg": "解析参数出错，请检查商品分类id参数",
		})
		return
	}

	r, err := global.GoodsSrvClient.GetCategoryBrandList(context.Background(), &proto.CategoryInfoRequest{
		Id: int32(idInt),
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, r)
}

// 获取"商品分类-品牌"的列表
func GetCategoryBrandList(ctx *gin.Context) {
	request := new(proto.CategoryBrandFilterRequest)

	pages := ctx.DefaultQuery("pn", "0")
	pagesInt, _ := strconv.Atoi(pages)
	request.Pages = int32(pagesInt)

	perNums := ctx.DefaultQuery("pnum", "0")
	perNumsInt, _ := strconv.Atoi(perNums)
	request.PagePerNums = int32(perNumsInt)

	rsp, err := global.GoodsSrvClient.CategoryBrandList(context.Background(), request)
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

// 添加商品分类-品牌关系
func AddCategorybrand(ctx *gin.Context) {
	f := new(forms.CreateCategorybrandForm)
	if err := ctx.ShouldBind(&f); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}

	rsp, err := global.GoodsSrvClient.CreateCategoryBrand(context.Background(), &proto.CategoryBrandRequest{
		CategoryId: f.CategoryId,
		BrandId:    f.BrandId,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

// 修改"商品分类-品牌"关系
func UpdateCategoBrand(ctx *gin.Context) {
	idStr := ctx.Param("id")
	idInt, err := strconv.Atoi(idStr)
	if err != nil {
		zap.S().Error("strconv.Atoi：string转int类型发生错误")
		ctx.JSON(http.StatusNotFound, gin.H{
			"msg": `解析参数出错，请检查[商品分类-品牌]id参数`,
		})
		return
	}

	raw, _ := ctx.GetRawData()
	f := new(forms.CreateCategorybrandForm)
	json.Unmarshal(raw, &f)

	_, err = global.GoodsSrvClient.UpdateCategoryBrand(context.Background(), &proto.CategoryBrandRequest{
		Id:         int32(idInt),
		CategoryId: f.CategoryId,
		BrandId:    f.BrandId,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"msg": "修改成功",
	})
}

// 删除"商品分类-品牌"记录
func DeleteCategorybrand(ctx *gin.Context) {
	idStr := ctx.Param("id")
	idInt, err := strconv.Atoi(idStr)
	if err != nil {
		zap.S().Error("strconv.Atoi：string转int类型发生错误")
		ctx.JSON(http.StatusNotFound, gin.H{
			"msg": `解析参数出错，请检查[商品分类-品牌]id参数`,
		})
		return
	}

	_, err = global.GoodsSrvClient.DeleteCategoryBrand(context.Background(), &proto.CategoryBrandRequest{
		Id: int32(idInt),
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
}
